import { _decorator, Component, EventTouch, log, Node, v3, Vec3 } from 'cc';
import { PlayerManager } from '../PlayerManager';
const { ccclass, property } = _decorator;
// 摇杆
@ccclass('joystick')
export class joystick extends Component {
    private isDragging = false;
    private offset = new Vec3();

    @property(Node)
    public player: Node = null;
    onLoad() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
    protected onDestroy(): void {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
    onTouchStart(event: EventTouch) {
        this.isDragging = true;
        
        // 计算触摸点与节点中心的偏移
        const touchPos = event.getUILocation();
        const nodePos = this.node.position;
        this.offset.set(nodePos.x - touchPos.x, nodePos.y - touchPos.y, 0);
        
        event.propagationStopped = true;
    }

    onTouchMove(event: EventTouch) {
        if (!this.isDragging) return;
        const touchPos = event.getUILocation();
        this.player.getComponent(PlayerManager).toMove(v3(touchPos.x + this.offset.x,touchPos.y + this.offset.y,0))
        
        this.node.setPosition(
            touchPos.x + this.offset.x,
            touchPos.y + this.offset.y,
            0
        );
    }

    onTouchEnd(event: EventTouch) {
        this.isDragging = false;
        this.node.setPosition(0, 0, 0);
          this.player.getComponent(PlayerManager).endMove()
    }
}


